package com.keur.money.utils.helper

import com.keur.money.app.MyApp
import com.keur.money.http.ApiService
import com.keur.money.http.ApiService.addCommonParams
import com.keur.money.http.ApiService.addRandomParams
import com.keur.money.http.HttpHelper
import com.keur.money.http.IHttpCallback
import com.keur.money.utils.event.KeurEventData
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/16 15:49
 * @Annotation：用户优惠券
 */
object KeurUserCouponHelper {

    /**
     * 获取优惠券列表
     */
    fun loadMullaUserCouponListAction(callback: IHttpCallback? = null){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_COUPON_LIST_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
            put("mobile", SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_MOBILE))
            put("infoType","scoreCouponInfo")
        }
        HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                callback?.onRequestSuccess(data)
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        SharedHelper.removeKeurData(SharedHelper.KEUR_SPKEY.KEUR_USER_COUPON_INFO)
                        if (obj != null){
                            val couponArray = obj.optJSONArray("couponList")
                            if (couponArray != null) {
                                SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_USER_COUPON_INFO,couponArray.toString())
                            }
                            MyApp.app.publisher.publish(KeurEventData(KeurEventData.TYPE.KEUR_COUPON_REFRESHED))
                        }
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                callback?.onRequestError(error)
            }

            override fun onRequestFinish() {
                callback?.onRequestFinish()
            }
        })
    }
}